package main

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"os/exec"
	"sync"
)

func main() {
	ctx := context.Background()
	c := exec.CommandContext(ctx, "bash", "-c", "more  /tmp/1.log")

	stdout, _ := c.StdoutPipe()
	stderr, _ := c.StderrPipe()


	var wg sync.WaitGroup
	// 因为有2个任务, 一个需要读取stderr 另一个需要读取stdout
	wg.Add(2)

	go read(ctx, &wg, stderr)
	go read(ctx, &wg, stdout)
	// 这里一定要用start,而不是run 详情请看下面的图
	err := c.Start()

	proState, err := c.Process.Wait()
	if err != nil {
		panic(err)
	}
	fmt.Println("waiting status-->", proState.String())
	// 等待任务结束
	wg.Wait()
	fmt.Println("----END------")
}

func read(ctx context.Context, wg *sync.WaitGroup, std io.ReadCloser) {
	reader := bufio.NewReader(std)
	defer wg.Done()
	for {
		select {
		case <-ctx.Done():
			return
		default:
			readString, err := reader.ReadString('\n')

			if err != nil || err == io.EOF {
				return
			}
			fmt.Print(readString)
		}
	}
}
